package com.luhui.codereview.swing

import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.psi.util.PsiUtilBase
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBPanel
import com.intellij.ui.components.JBScrollPane
import com.luhui.codereview.api.ApiManager
import com.luhui.codereview.dto.CreateCodeReviewDto
import com.luhui.codereview.enums.CodeReviewLevelEnum
import com.luhui.codereview.getMessage
import com.luhui.codereview.service.ProjectService
import com.luhui.codereview.token.LocalUserInfoHodler
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.apache.commons.lang.StringUtils
import retrofit2.Call
import retrofit2.Response
import java.awt.EventQueue
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.Insets
import javax.swing.JButton
import javax.swing.JComboBox
import javax.swing.JTextArea

/**
 * @author  luhui
 * @date  2019/11/18 21:42
 * @version 1.0
 */
class CreateCodeReviewTab(
        private val viewTabTableApplication: ViewTabTable.ViewTabTableApplication,
        private val project: Project
) : JBPanel<JBPanel<*>>(){

    /**
     * 代码
     */
    val codeTextArea:JTextArea

    /**
     *  备注textArea
     */
    val contentTextArea:JTextArea

    init {
        val lay= GridBagLayout()
        this.layout = lay
        val c=  GridBagConstraints()
        c.fill= GridBagConstraints.BOTH
        c.gridwidth=1
        c.gridheight=1
        addLabel(this,lay,c, getMessage("createCodeReviewTab.codeLabel.text"))
        c.gridwidth= GridBagConstraints.REMAINDER
        c.gridheight= GridBagConstraints.RELATIVE
        c.weighty=1.0
        c.weightx=1.0
        c.gridheight=2
        val text = JTextArea(1,1)
        this.codeTextArea = text
        this.viewTabTableApplication.origCodeTextArea = text

        val textPanel = JBScrollPane(text)
        lay.setConstraints(textPanel, c)
        text.isEditable = false
        this.add(textPanel)
        c.weighty=0.0
        c.weightx=0.0
        c.gridwidth=1
        c.gridheight=1
        c.insets= Insets(5,0,0,0)
        addLabel(this,lay,c, getMessage("createCodeReviewTab.codeProblemLabel.text"))
        c.gridwidth= GridBagConstraints.REMAINDER
        c.gridheight= GridBagConstraints.RELATIVE
        c.weighty=1.0
        c.weightx=1.0
        c.gridheight=2
        val contextText = JTextArea(1,1)
        this.contentTextArea = contextText
        val contextTextPanel = JBScrollPane(contextText)
        lay.setConstraints(contextTextPanel, c)
        viewTabTableApplication.contextTestArea = contextText
        this.add(contextTextPanel)


        c.gridheight= GridBagConstraints.REMAINDER
        c.weighty=0.0
        c.gridheight=1

        val btnPanel = createBtnPanel()
        lay.setConstraints(btnPanel,c)
        this.add(btnPanel)
    }

    private fun addLabel(panel:JBPanel<JBPanel<*>>,lay:GridBagLayout,c:GridBagConstraints,name:String){
        val bt= JBLabel(name)
        lay.setConstraints(bt, c)
        panel.add(bt)
    }

    private fun createBtnPanel():JBPanel<JBPanel<*>>{
        val btnPanel= JBPanel<JBPanel<*>>()

        btnPanel.add(JBLabel(getMessage("createCodeReviewTab.assignText")))
        val assigneeComboBox = JComboBox(arrayOf("所有人"))
        btnPanel.add(assigneeComboBox)

        btnPanel.add(JBLabel(getMessage("createCodeReviewTab.errorLevelText")))
        val levelComboBox = JComboBox(CodeReviewLevelEnum.getAllEnumValues())
        viewTabTableApplication.levelComboBox = levelComboBox
        btnPanel.add(levelComboBox)

        val saveBtn = JButton(getMessage("createCodeReviewTab.saveBtnText"))
        saveBtn.addActionListener {
            val fileEditorManager = FileEditorManager.getInstance(project) ?: return@addActionListener
            val editor = fileEditorManager.selectedTextEditor?:return@addActionListener
            //在Editor中位置分为两种，一种是逻辑位置，对应LogicalPosition类；另一种是视觉位置，对应VisualPosition类。具体介绍见：https://www.jianshu.com/p/59a0826841fe
            val startPosition = editor.selectionModel.selectionStartPosition?.let { editor.visualToLogicalPosition(it) } ?: return@addActionListener
            editor.selectionModel.selectionStartPosition
            val endPosition = editor.selectionModel.selectionEndPosition?.let { editor.visualToLogicalPosition(it) }   ?: return@addActionListener

            //todo 不要去访问业务对象中的
            val selectCode = this.codeTextArea.text

            //todo 不要去访问application
            val context = this.contentTextArea.text
            val filepath = PsiUtilBase.getPsiFileInEditor(editor,project)!!.viewProvider.virtualFile.path.substring(project.basePath!!.length+1)
            if(StringUtils.isBlank(selectCode)){
                Messages.showErrorDialog(getMessage("saveCode.codeIsNull.msg"), getMessage("codeReview"))
                return@addActionListener
            }
            if(StringUtils.isBlank(context)||context!!.length<5){
                Messages.showErrorDialog(getMessage("saveCode.context.lengthLt5"), getMessage("codeReview"))
                return@addActionListener
            }

            val projectId = ProjectService.getInstance(project).getCurrentProjectInfo()?.id
            if(projectId==null){
                Messages.showErrorDialog(getMessage("notFoundProjectId.msg"), getMessage("notFoundProjectId.title"))
                return@addActionListener
            }

            val createCodeReviewDto = CreateCodeReviewDto(projectId,filepath,startPosition.line,endPosition.line,
                    startPosition.column,endPosition.column,selectCode?:"", CodeReviewLevelEnum.getCodeByDesc(levelComboBox.selectedItem.toString())!!, context,
                    LocalUserInfoHodler.localUserInfo?.id!!,2)

            GlobalScope.launch{
                val result = ApiManager.getApiInstance().saveCodeReview(createCodeReviewDto)
                if(!result){
                    EventQueue.invokeLater {
                        Messages.showMessageDialog(getMessage("saveCodeReviewErrorMsg"), getMessage("codeReview"),null)
                    }
                }
                codeTextArea.text = ""
                contentTextArea.text = ""
            }

        }
        btnPanel.add(saveBtn)
        return btnPanel
    }

}